package app.cryp;

public class HexUtils {

	public static final String HEX = "0123456789abcdef";

	public static String bytesToHex(byte[] bytes) {
		if (bytes != null && bytes.length > 0) {
			StringBuilder builder = new StringBuilder(bytes.length * 2);
			for (byte b : bytes) {
				// 取出这个字节的高4位，然后与0x0f与运算，得到一个0-15之间的数据，通过HEX.charAt(0-15)即为16进制数
				builder.append(HEX.charAt((b >> 4) & 0x0f));
				// 取出这个字节的低位，与0x0f与运算，得到一个0-15之间的数据，通过HEX.charAt(0-15)即为16进制数
				builder.append(HEX.charAt(b & 0x0f));
			}

			return builder.toString();
		}
		return null;
	}

	public static byte[] hexToBytes(String hexString) {
		if (hexString != null && hexString.length() != 0) {
			int length = hexString.length() / 2;
			char[] hexChars = hexString.toCharArray();
			byte[] bytes = new byte[length];
			for (int i = 0; i < length; i++) {
				int pos = i * 2;
				bytes[i] = (byte) ((((byte) (HEX.indexOf(hexChars[pos])) << 4) | ((byte) (HEX
						.indexOf(hexChars[pos + 1])))));
			}
			return bytes;
		}

		return null;
	}
}
